#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "task.h"

typedef void(*func_t)();
#define N 3
func_t tasks[N] = {NULL};

void LoadTask()
{
  tasks[0] = PrintLog;
  tasks[1] = DownLoad;
  tasks[2] = MysqlDataSync;
}

void HandlerTask()
{
  for(int i = 0; i < N; i++)
  {
    tasks[i]();
  }
}

void DoOtherThing()
{
  HandlerTask();
}

void ChileRun()
{
  int cnt = 5;
  while(cnt)
  {
    printf("I am child process, pid:%d, ppid:%d, cnt:%d\n", getpid(), getppid(), cnt);
    sleep(2);
    cnt--;
  }
}

int main()
{
  printf("I am father , pid:%d, ppid:%d\n", getpid(), getppid());
  
  pid_t id = fork();
  if(id == 0)
  {
   ChileRun();
    printf("child quit ...\n");
    exit(123);
  }
  LoadTask();
  //father
  while(1)
  {
    int status = 0;
    pid_t rid = waitpid(id , &status, WNOHANG);
    if(rid == 0)
    {
      printf("child is running , father check next time\n");
      sleep(1);
      DoOtherThing();
    }
    else if(id > 0)
    {
      if(WIFEXITED(status))
      {
        printf("child quit success , child exit code : %d\n", WEXITSTATUS(status));
      }
      else
      {
        printf("child quit unormal!\n");
      }
      break;
    }
    else
    {
      printf("waitpid failed!\n");
      break;
    }
  }
}
